import subprocess
from somenzz.decorators import timeit
import re
from datetime import timedelta
import socket
import time

def get_local_ip():
    return socket.gethostbyname(socket.gethostname())


def chmod777(file_path):
    command = f'''ssh root@localhost "chmod 777 {file_path}"'''
    subprocess.run(command, shell=True)

@timeit()
def convert_encoding(src,dst,from_encoding, to_encoding):
    command = f'iconv -f {from_encoding} -t {to_encoding} -c {src} -o {dst}'
    r = subprocess.run(command, shell = True)
    return r.returncode


def replace_yyyymmdd(text, date):
    rq10 = date.strftime("%Y-%m-%d")
    rq8 = date.strftime("%Y%m%d")
    year = date.strftime("%Y")
    year_month = date.strftime("%Y%m")
    year_and_month = date.strftime("%Y-%m")
    day = date.strftime("%d")
    month = date.strftime("%m")
    month_and_day = month + day
    time_total_seconds = int(time.time())
    text = re.sub("#YYYY-MM-DD#", rq10, text, flags=re.I | re.M)
    text = re.sub("#YYYYMMDD#", rq8, text, flags=re.I | re.M)
    text = re.sub("#YYYY-MM#", year_and_month, text, flags=re.I | re.M)
    text = re.sub("#YYYYMM#", year_month, text, flags=re.I | re.M)
    text = re.sub("#YYYY#", year, text, flags=re.I | re.M)
    text = re.sub("#DD#", day, text, flags=re.I | re.M)
    text = re.sub("#MM#", month, text, flags=re.I | re.M)
    text = re.sub("#MMDD#", month_and_day, text, flags=re.I | re.M)
    text = re.sub("#TIME%s#", str(time_total_seconds), text, flags=re.M)

    special = re.search("#YYYYMMDD[+-]\d+D#", text, re.I | re.M)  # 处理8位日期加减指定天数
    if special:
        regex = special.group()  # regex=#yyyymmdd+1D#
        days = int(regex[10:-2])

        calcu_date = date
        if regex[9] == '+':
            calcu_date = date + timedelta(days=days)
        elif regex[9] == '-':
            calcu_date = date - timedelta(days=days)

        text = re.sub(
            "#YYYYMMDD[+-]\d+D#", calcu_date.strftime("%Y%m%d"), text, flags=re.I | re.M
        )
    return text
